package com.atguigu.flow.demo;


import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.atguigu.flow.entity.*;
import com.atguigu.flow.entity.vo.Module_Field;


import com.atguigu.flow.entity.vo.Noclude_Field;
import com.atguigu.flow.entity.vo.Permissions;
import com.atguigu.flow.mapper.*;
import com.atguigu.flow.service.IwInstanceService;

import com.atguigu.flow.utils.*;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.SocketUtils;
import org.springframework.util.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @author: kw
 * @description: 签名连通测试
 * @create: 2021/11/18 15:16
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@MapperScan("com.atguigu.flow.mapper")

public
class xml_test {



    @Autowired
    SqlMapper sqlMapper;

    @Autowired
    private IwInstanceMapper instanceMapper;
    @Autowired
    private IwTaskMapper iwTaskMapper;

    @Autowired
    private
    IwInstanceService iwInstanceService;
    @Autowired
    private
    Workflow workflow;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private ItemsMapper itemsMapper;
    @Autowired
    private ItemsQuoteMapper itemsQuoteMapper;




    @Autowired
    private SysAttachmentMapper sysAttachmentMapper;
    @Autowired
    private AttachmentSave attachmentSave;
    @Autowired
    GetFlowModule_field_util getFlowModule_field_util;
    @Autowired
    private ShipmentApplyMapper shipmentApplyMapper;
    @Autowired
    private  XmlTest xmlTest;


    private static final Logger logapp = LoggerFactory.getLogger("applog");

    @Test
    public void attachmenttobase64() throws Exception {
       String parentid="608A3F5D-F021-444F-B0C3-6BC3724E1822";
       String recordid="8F8A5E73-8D47-4431-B309-86C4E82DCA1B";
       String filename="FORNORD.pdf";
       JSONObject json=attachmentSave.attachmenttobase64(parentid,recordid,filename);
        System.out.println(json);
       if (json.containsKey("Base64")){
           if (!json.getString("Base64").isEmpty())


        Base64Util.base64ToFile("d:\\",json.getString("Base64"),filename);}

    }

    @Test
    public
    void test_dateformat() {
        String str = DateUtil.formatDate_spec(new Date(), "yyyy-MM-dd") + "T" + DateUtil.formatDate_spec(new Date(), "HH:mm:ss.SSS");
        System.out.println(str);
    }
    @Test
    public void get_userid(){
        String userid=sqlMapper.get_userid("蔡辉");
        System.out.println(userid);
    }
    @Test
    public void test_editfield() throws DocumentException, ParseException {
//        String str=getFlowModule_field_util.getflowspname("Self.QueryRecordValue('追加后总额度')", "4E56FBF4-F0B9-422E-A129-C0FB130B184B", "赊销额度申请");
//      float hj=Float.parseFloat(str);
//        System.out.println(hj);
//
        String nbhs="A32ED";
        Boolean is=nbhs.contains("A32");
        System.out.println(is);



    }

    @Test
    public
    void base64_decode() {
//        String str = "77u/dXNlcw0KICBTeXNVdGlscywgVmFyaWFudHMsIENsYXNzZXMsIGN4Rmxvd0VuZ2luZSwgY3hR\n" +
//                "dWVyeTsNCg0KcHJvY2VkdXJlIERvQ2FsY0V4ZWN1dG9yUmFuZ2UoU2VuZGVyOiBUT2JqZWN0OyB2\n" +
//                "YXIgQVJlc3VsdDogc3RyaW5nKTsNCnZhcg0KIFE6IFRjeFF1ZXJ5Ow0KYmVnaW4NCiAgUSA6PSBU\n" +
//                "Y3hRdWVyeS5DcmVhdGUobmlsKTsNCiAgdHJ5ICAgDQogICAgUS5TUUwuVGV4dCA6PSAnU0VMRUNU\n" +
//                "IGJtamwgRlJPTSBEaWNfRW1wbG95ZWUgV0hFUkUgRW1wbG95ZWVDSE5uYW1lID0gOkVtcGxveWVl\n" +
//                "Q0hObmFtZSc7IA0KICAgIFEuUGFyYW1CeU5hbWUoJ0VtcGxveWVlQ0hObmFtZScpLlZhbHVlIDo9\n" +
//                "IFNlbGYuUXVlcnlSZWNvcmRWYWx1ZSgn6Lef5Y2V5ZGYJyk7DQogICAgUS5PcGVuOw0KICAgIGlm\n" +
//                "IG5vdCBRLklzRW1wdHkgdGhlbiAgICAgDQogICAgICBBUmVzdWx0IDo9IFNlbGYuQ29udmVydFVz\n" +
//                "ZXJOYW1lVG9JRChRLkZpZWxkQnlOYW1lKCdibWpsJykuQXNTdHJpbmcpDQogICAgZWxzZSAgDQog\n" +
//                "ICAgICBBUmVzdWx0IDo9IFNlbGYuQ29udmVydFVzZXJOYW1lVG9JRCgn5YiY6YeR6bmPJyk7ICAg\n" +
//                "Ly/lvILluLjlpITnkIYgIA0KICBmaW5hbGx5DQogICAgRnJlZUFuZE5pbChRKTsNCiAgZW5kOw0K\n" +
//                "ZW5kOw0K";
        String str="316AD814AB9CFFC69A775F8F2A02E5DE";
        String rlt1 = new String(Base64.decode(str));
        System.out.println("new String===" + rlt1);
    }

    @Test
    public
    void test_date() throws ParseException {
        Date date=DateUtil.StringTodatetime("1900-01-01 00:00:00");
        System.out.println(date);
    }

    @Test
    public
    void
    flow_agree_service() throws Exception {
//        String recordid = "FC6EA21F-B21F-4CDE-98B3-FB765ADD2893";
//        String modulename = "工厂资料";
//        String str=iwInstanceService.flow_agree(recordid,modulename,true);
//        System.out.println(str);
        String recordid = "888B18CA-0CF4-4A58-944E-503D5B567567";
        String modulename = "客户资料";
        String str = iwInstanceService.flow_agree(recordid, modulename, true);
        System.out.println(str);
    }

    @Test
    public void show_salesoreder_flow() throws  Exception {

        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
        String recordid = "36DAE0DC-7674-4868-BCBF-6A5AE26AE7A9";
        String modulename = "外销合同";
        wrapper.select("top 1 * ");
        wrapper.eq("RecordID", recordid)
                .eq("Module", modulename)
                .eq("Deleted", 0);
        //.orderByDesc("serialid");

        Integer count = instanceMapper.selectCount(wrapper);
        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
        Map<String, Object> params = new HashMap<>();
        if (count > 0) {
            wrapper.orderByDesc("serialid");
            IwInstance iwInstance = instanceMapper.selectOne(wrapper);
            System.out.println(iwInstance.getFlowData());

        }

    }


    @Test
    public void show_flowxml() throws  Exception {

        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
        String recordid = "C2BD6F01-E284-48A5-9398-F695ACD76A62";
        String modulename = "工厂资料";
        wrapper.select("top 1 * ");
        wrapper.eq("RecordID", recordid)
                .eq("Module", modulename)
                .eq("Deleted", 0);
        //.orderByDesc("serialid");

        Integer count = instanceMapper.selectCount(wrapper);
        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
        Map<String, Object> params = new HashMap<>();
        if (count > 0) {
            wrapper.orderByDesc("serialid");
            IwInstance iwInstance = instanceMapper.selectOne(wrapper);
            System.out.println(iwInstance.getFlowData());

        }

    }
    @Test
    public
    void
    flow_agree_seqdservice() throws Exception{
        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
        String modulename = "赊销额度申请";
        Boolean isgree=true;
        String str=iwInstanceService.flow_agree(recordid,modulename,isgree);
        System.out.println(str);


    }
    @Test
    public
    void
    flow_agree() throws DocumentException, ParseException, IOException {
//        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
//        String recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
//        String modulename = "赊销额度申请";
//        wrapper.select("top 1 * ");
//        wrapper.eq("RecordID", recordid)
//                .eq("Module", modulename)
//                .eq("Deleted", 0);
//        //.orderByDesc("serialid");
//
//        Integer count = instanceMapper.selectCount(wrapper);
//        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
//        Map<String, Object> params = new HashMap<>();
//        if (count > 0) {
//            wrapper.orderByDesc("serialid");
//            IwInstance iwInstance = instanceMapper.selectOne(wrapper);
//            QueryWrapper<IwTask> taskQueryWrapper = new QueryWrapper<>();
//            taskQueryWrapper.select("top 1 * ");
//            taskQueryWrapper.eq("InstanceID", iwInstance.getInstanceID())
//                    .eq("Deleted", 0)
//                    .orderByDesc("serialid");
//            IwTask iwTask = iwTaskMapper.selectOne(taskQueryWrapper);
//
//
//            String xml = iwInstance.getFlowData();
//            //System.out.println(xml);
//            Document doc = null;
//            doc = DocumentHelper.parseText(xml);
//            Element rootElt = doc.getRootElement();
////            System.out.println("1--"+rootElt.getDocument());
//            //System.out.println("2--"+rootElt.asXML());
//            params.clear();
//            getFlowModule_field_util.ative_elemnt(recordid, modulename, rootElt, true, params);
//            Document document = DocumentHelper.parseText(rootElt.asXML());
//
//            if (!StringUtils.isEmpty(params) && params.size() > 0) {
//                iwInstance.setCurrentFlowActivity(params.get("CurrentFlowActivity").toString());
//                iwInstance.setLastFlowActivity(params.get("LastFlowActivity").toString());
//                //iwInstance.setTaskid(params.get("TaskID").toString());
//                if (params.get("CurrentFlowActivity").toString().equals("已结束"))
//                    iwInstance.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
//                iwInstance.setFlowData(document.asXML());
//                count = instanceMapper.update_flowdata(iwInstance);
//                System.out.println("流程表更新" + Integer.valueOf(count));
//                System.out.println(count);
//                String filepath = "d:\\xml/" + params.get("unitname").toString() + ".xml";
//                OutputFormat outputFormat = new OutputFormat();
//                outputFormat.setEncoding("UTF-8");
//                OutputStream outputStream = null;
//                outputStream = new FileOutputStream(filepath);
//                XMLWriter xmlWriter = new XMLWriter(outputStream, outputFormat);
//
//                xmlWriter.write(document);
//
////                //检测是否存在该目录
////                if (!dest.getParentFile().exists()) {
////                    dest.getParentFile().mkdirs();
////                }
////                XMLWriter write = new XMLWriter(
////                        new FileWriter(filepath)
////                );
////                write.write(document);
////                write.close();
//                if (!StringUtils.isEmpty(iwTask)) {
////                    if (!params.containsKey("endflow")){
//                    iwTask.setFinishTime(DateUtil.StringTodatetime((params.get("FinishTime").toString())));
//                    iwTask.setState(Integer.valueOf(params.get("State").toString()));
//                    count = iwTaskMapper.update_flowdata(iwTask);
//                    System.out.println("任务表更新" + Integer.valueOf(count));
////                    if (!params.get("CurrentFlowActivity").toString().equals("EndUnit")){
//                    if (!params.containsKey("endflow")) {
//                        iwTask.setSerialID(null);
//                        iwTask.setTaskID(params.get("TaskID").toString());
//                        iwTask.setUnitName(params.get("unitname").toString());
//                        iwTask.setExecutor(params.get("Executor").toString());
//                        iwTask.setState(0);
//                        iwTask.setFinishTime(null);
//                        iwTask.setReceiveTime(DateUtil.StringTodatetime((params.get("ReceiveTime").toString())));
//                        iwTask.setSubject(params.get("subject").toString());
//                        iwTask.setDeleted(false);
//                        count = iwTaskMapper.insert(iwTask);
//                        System.out.println("任务表新增" + Integer.valueOf(count));
//                    }
//
//
//                }
//                System.out.println(params);
//                System.out.print(iwInstance);
//                System.out.print(iwTask);
//
//            }


//        }


        //System.out.println(document.asXML());
        //System.out.println(getFlowModule_field_util.sybjl("赊销额度申请","jlsp","钱临波2"));
        //写入emp1.xml文件
        //writerDocumentToNewFile(document);


        //System.out.println(str);

    }


    @Test
    public
    void
    read_flow() throws DocumentException {
        QueryWrapper<IwInstance> wrapper = new QueryWrapper<>();
        wrapper.select("top 1 * ");
        wrapper.eq("RecordID", "4E56FBF4-F0B9-422E-A129-C0FB130B184B")
                .eq("Module", "赊销额度申请")
                .eq("Deleted", 0);
        //.orderByDesc("serialid");

        Integer count = instanceMapper.selectCount(wrapper);
        List<IwFlow> iwFlowList1 = new ArrayList<IwFlow>();
        Map<String, Object> params = new HashMap<>();
        if (count > 0) {
            wrapper.orderByDesc("serialid");
            IwInstance iwInstance = instanceMapper.selectOne(wrapper);
            String xml = iwInstance.getFlowData();
            System.out.println(xml);
            Document doc = null;
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            Element lNodeList = (Element) rootElt.selectSingleNode("/data/TcxFlow/Objects/TcxFlowStartUnit");
            IwFlow iwFlow = new IwFlow();
            iwFlow.setUnittype("TcxFlowStartUnit");
            iwFlow.setUnitName(lNodeList.selectSingleNode("Name").getStringValue());
            iwFlow.setNextUnit(lNodeList.selectSingleNode("NextUnit").getStringValue());
            if (!StringUtils.isEmpty(lNodeList.selectSingleNode("RuntimeProperties"))) {
                iwFlow.setState(lNodeList.selectSingleNode("RuntimeProperties/State").getStringValue());
            }
            Workflow.find_nextlevel(rootElt, iwFlow.getNextUnit());
//            Zxb_receivedata.find_nextlevel(rootElt,"bmzgsp");
//            System.out.println(Zxb_receivedata.iwFlowList);
//            Zxb_receivedata.find_nextlevel(rootElt,"bmjlsp");
            if (Workflow.iwFlowList.size() > 0) {
                for (int i = 0; i <= Workflow.iwFlowList.size() - 1; i++) {
                    iwFlow = Workflow.iwFlowList.get(i);
                    if (!StringUtils.isEmpty(iwFlow.getExecutor())
                            && !StringUtils.isEmpty(iwFlow.getSender())) {
                        params.clear();
                        params.put("sql", "select dbo.getusername(#{Senderid}) as Sender,dbo.getusername(#{Executorid}) as Executor");
                        params.put("Senderid", iwFlow.getSender());
                        params.put("Executorid", iwFlow.getExecutor());
                        List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                        if (ans.size() > 0) {
                            Map<String, Object> mapList = ans.get(0);
                            iwFlow.setSender(mapList.get("Sender").toString());
                            iwFlow.setExecutor(mapList.get("Executor").toString());
                        }

                    }

                }
            }
            System.out.println(JSON.toJSONString(Workflow.iwFlowList));


            //System.out.println(lNodeList.asXML());
            //Iterator iterator = lNodeList.elementIterator();
//            while (iterator.hasNext()) {
//
//
//                Element stuChild = (Element) iterator.next();
//                System.out.println("节点名：" + stuChild.getName() + "---节点值：" + stuChild.getStringValue());
//            }

//
//            //System.out.println(subitem);
//
//            List<Element>  ActivityNodeList =  rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowActivityUnit");
//            for (int i=0;i<=ActivityNodeList.size()-1;i++){
//                Element  lNodeItem= ActivityNodeList.get(i);
//                IwFlow iwFlow=new IwFlow();
//                iwFlow.setUnittype("TcxFlowActivityUnit");
//                iwFlow.setUnitName(lNodeItem.selectSingleNode("Name").getStringValue() );
//
//                //temptable.FieldByName('unitcaption').AsString:= lNodeItem.selectSingleNode('Caption').text;
//                //
//                //            temptable.FieldByName('NextUnit').AsString:= lNodeItem.selectSingleNode('NextUnit').text;
//                iwFlow.setUnitcaption(lNodeItem.selectSingleNode("Caption").getStringValue());
//                iwFlow.setNextUnit(lNodeItem.selectSingleNode("NextUnit").getStringValue());
//                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("ExecuteProperties"))){
//                    iwFlow.setExecutor(lNodeItem.selectSingleNode("ExecuteProperties/ExecutorRange").getStringValue());
//                }
//
//                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))){
//                    iwFlow.setState(lNodeItem.selectSingleNode("RuntimeProperties/State").getStringValue());
//
//                    List<Element>  tasklist=lNodeItem.selectNodes("RuntimeProperties/Tasks/Item");
//                    Element taskitem=tasklist.get(0);
//                    if (tasklist.size()>1)    taskitem=tasklist.get(tasklist.size()-1);
//                    params.clear();
//                    params.put("sql", "select dbo.getusername(#{Senderid}) as Sender,dbo.getusername(#{Executorid}) as Executor");
//                    params.put("Senderid", taskitem.selectSingleNode("Sender").getStringValue());
//                    params.put("Executorid", taskitem.selectSingleNode("Executor").getStringValue());
//                    List<Map<String, Object>> ans = sqlMapper.sqltest(params);
//                    if (ans.size() > 0) {
//                        Map<String, Object> mapList = ans.get(0);
//                        iwFlow.setSender(mapList.get("Sender").toString());
//                        iwFlow.setExecutor(mapList.get("Executor").toString());
//                    }
//
//
//
////                    iwFlow.setExecutor(taskitem.selectSingleNode("Executor").getStringValue());
////                    iwFlow.setSender(taskitem.selectSingleNode("Sender").getStringValue());
//                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits")))
//                    iwFlow.setFlowFromUnits(lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").getStringValue());
//
//                }
//                iwFlowList.add(iwFlow);
//
//            }
            //System.out.println(iwFlowList);

//            List nodes = rootElm.elements("member");
//            for (Iterator it = nodes.iterator(); it.hasNext();) {
//                Element elm = (Element) it.next();
//                // do something
//            }




            /*
             * 签名验签
             *
             *
             */
        }
    }





    public
    void getNodes(Element node, String parentname) {
        System.out.println("--------------------");

        //当前节点的名称、文本内容和属性
        System.out.println("当前节点名称/父节点名称" + node.getName() + "/" + parentname);//当前节点名称
        System.out.println("当前节点的内容：" + node.getTextTrim());//当前节点名称

        List<Attribute> listAttr = node.attributes();//当前节点的所有属性的list
        for (Attribute attr : listAttr) {//遍历当前节点的所有属性
            String name = attr.getName();//属性名称
            String value = attr.getValue();//属性的值
            System.out.println("属性名称：" + name + "属性值：" + value);
        }

        //递归遍历当前节点所有的子节点
        List<Element> listElement = node.elements();//所有一级子节点的list
        System.out.println("当前节点名称：" + node.getName() + "节点数量" + listElement.size());

        for (Element e : listElement) {//遍历所有一级子节点
            this.getNodes(e, node.getName());//递归
        }
    }






    //测试账套
    @Test
    public
    void test_projxml() throws Exception {
        List<Module_Field> module_fieldList = Workflow.getmodle_fieldlist("出运申报");
        //System.out.println(module_fieldList);
        String str = "发票编号,发票金额,投保金额,出运货币代码,合同支付期限,出运日期";
        String[] fieldarray = str.split(",");
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        Map<String, Object> hashMapresult = new HashMap<String, Object>();

        for (String arrstr : fieldarray) {
            List<Module_Field> module_fieldList_temp = new ArrayList<Module_Field>();
            module_fieldList_temp = module_fieldList.stream().filter(user -> arrstr.equals(user.getName())).collect(Collectors.toList());

            System.out.println(module_fieldList_temp);
            if (module_fieldList_temp.size() > 0) {


                Module_Field module_field = module_fieldList_temp.get(0);
                hashMap.put( module_field.getFieldname(),arrstr);
            }
        }
//        System.out.println(hashMap);
        QueryWrapper<ShipmentApply> wrapper = new QueryWrapper();
        wrapper.likeRight("invoiceNo", "A24").
                and(qw -> qw.eq("payTerm1", 45).or().eq("payTerm1", 90));
        List<ShipmentApply> shipmentApplyList = shipmentApplyMapper.selectList(wrapper);
        for (int i=0;i<=shipmentApplyList.size()-1;i++){
            ShipmentApply shipmentApply=shipmentApplyList.get(i);
            hashMapresult= BeanTomap.replaceContext(ShipmentApply.class, shipmentApply, hashMap);
            System.out.println("hashMapresult:"+hashMapresult);

        }



    }

    @Test
    public
    void test_code_base() {
        String str = "<![CDATA[77u/dXNlcw0KICBTeXNVdGlscywgVmFyaWFudHMsIENsYXNzZXMsIGN4Rmxvd0VuZ2luZSwgY3hR\n" +
                "dWVyeTsNCg0KcHJvY2VkdXJlIERvQ2FsY0V4ZWN1dG9yUmFuZ2UoU2VuZGVyOiBUT2JqZWN0OyB2\n" +
                "YXIgQVJlc3VsdDogc3RyaW5nKTsNCnZhcg0KICBzWlcsIHNMZWFkZXI6IHN0cmluZzsNCiAgUTog\n" +
                "VGN4UXVlcnk7DQpiZWdpbg0KICBRIDo9IFRjeFF1ZXJ5LkNyZWF0ZShuaWwpOw0KICB0cnkNCiAg\n" +
                "ICBRLlNRTC5UZXh0IDo9ICdTRUxFQ1QgRW1wbG95ZWVDSE5uYW1lLCBNYW5hZ2VyLCBibWpsLCB6\n" +
                "d2xiIEZST00gRGljX0VtcGxveWVlIFdIRVJFIEVtcGxveWVlQ0hObmFtZSA9IDpFbXBsb3llZUNI\n" +
                "Tm5hbWUnOw0KICAgIFEuUGFyYW1CeU5hbWUoJ0VtcGxveWVlQ0hObmFtZScpLlZhbHVlIDo9IFZh\n" +
                "clRvU3RyKFNlbGYuUXVlcnlSZWNvcmRWYWx1ZSgn55Sz6K+35Lq6JykpOw0KICAgIFEuT3BlbjsN\n" +
                "CiAgICBpZiBub3QgUS5Jc0VtcHR5IHRoZW4gYmVnaW4NCiAgICAgIHNaVyA6PSBRLkZpZWxkQnlO\n" +
                "YW1lKCd6d2xiJykuQXNTdHJpbmc7DQogICAgICBpZiBzWlcgPSAn6Lef5Y2V5ZGYJyB0aGVuIC8v\n" +
                "5b2T5YmN5Y2V5a2Q5pivIOi3n+WNleWRmCDlj5HotbfnmoTvvIzliJnovazliLDkuJrliqHkuLvn\n" +
                "rqENCiAgICAgICAgc0xlYWRlciA6PSBRLkZpZWxkQnlOYW1lKCdibWpsJykuQXNTdHJpbmcNCiAg\n" +
                "ICAgIGVsc2UgaWYgc1pXID0gJ+S4muWKoeS4u+euoScgdGhlbiAvL+W9k+WJjeWNleWtkOaYryDk\n" +
                "uJrliqHkuLvnrqEg5Y+R6LW355qE77yM5YiZ6L2s5Yiw5LqL5Lia6YOo57uP55CGDQogICAgICAg\n" +
                "IHNMZWFkZXIgOj0gUS5GaWVsZEJ5TmFtZSgnYm1qbCcpLkFzU3RyaW5nDQogICAgICBlbHNlIGlm\n" +
                "IHNaVyA9ICfkuovkuJrpg6jnu4/nkIYnIHRoZW4gLy/lvZPliY3ljZXlrZDmmK8g5Yiw5LqL5Lia\n" +
                "6YOo57uP55CGIOWPkei1t+eahO+8jOWImee7meiHquW3sQ0KICAgICAgICBzTGVhZGVyIDo9IFEu\n" +
                "RmllbGRCeU5hbWUoJ2JtamwnKS5Bc1N0cmluZw0KICAgICAgZWxzZSAvL+WFtuS7luaDheWGtQ0K\n" +
                "ICAgICAgICBzTGVhZGVyIDo9IFEuRmllbGRCeU5hbWUoJ2JtamwnKS5Bc1N0cmluZzsNCg0KICAg\n" +
                "ICAgQVJlc3VsdCA6PSBTZWxmLkNvbnZlcnRVc2VyTmFtZVRvSUQoc0xlYWRlcik7IC8v5byC5bi4\n" +
                "5aSE55CGDQogICAgZW5kDQogICAgZWxzZQ0KICAgICAgQVJlc3VsdCA6PSBTZWxmLkNvbnZlcnRV\n" +
                "c2VyTmFtZVRvSUQoJ+WImOmHkem5jycpOyAvL+W8guW4uOWkhOeQhg0KICBmaW5hbGx5DQogICAg\n" +
                "RnJlZUFuZE5pbChRKTsNCiAgZW5kOw0KZW5kOw0K]]>";

        str = str.replace("![CDATA[", "");
        str = str.replace("]]", "");
        str = str.replace("<", "");
        str = str.replace(">", "");
        System.out.println(str);
        String rlt1 = new String(Base64.decode(str));
        System.out.println("new String===" + rlt1);

//        String regex="\\[(.*?)\\]";
//         Pattern p=Pattern.compile(regex);
//        Matcher m=p.matcher(str);
//        System.out.println(m);
//        while(m.find()) {
//            String str1 = m.group(1);
//            System.out.println(str1);
//        }
//
//
//        String patternStr = "^(?<date>\\d{8})\\.(?<cluster>\\w*)\\.(?<index>\\w*)\\.(?<operation>create|update)\\.(?<ohter>.*)$";
//        Pattern pattern = Pattern.compile(patternStr);
//
//        String testStr1 = "20190317.cluster.index.create.yml";
//        String testStr2 = "20190318.cluster.index.update.yml";
//        String testStr3 = "20190319.cluster.index.delete.yml";
//
//        List<String> testList = Arrays.asList(testStr1, testStr2, testStr3);
//
//        testList.stream()
//                .map(test -> pattern.matcher(test))
//                .forEach(matcher -> {
//                    if (matcher.matches()) {
//                        System.out.println(matcher.group("date"));
//                        System.out.println(matcher.group("cluster"));
//                        System.out.println(matcher.group("operation"));
//                    }
//                });
//

    }

    @Test
    public
    void copyfile() throws Exception {
        String filename = "2018年初中历史：世界古代史近代史-殖民扩张与殖民地人民的抗争.pdf";
        String filepath = "E:\\初中课程";
        filepath = filepath + "/" + filename;
        File file = new File(filepath);
        if (file.exists()) {
            byte[] datas = Zxb_receivedata.convertFileToByteArray(filepath);
            System.out.println(datas);
            String datePath = DateUtil.fileformatDate(new Date());
            filename = "E:\\pic_upload\\" + datePath + "/" + filename;
            ;
            File dest = new File(filename);
            //检测是否存在该目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            Zxb_receivedata.convertByteArrayToFile(filename, datas);

        }


    }

    @Test
    public
    void getflowcon() throws DocumentException {


        String str = "Self.QueryRecordValue('最后修改人')<>'王露雷'";





        String recordid = "C2BD6F01-E284-48A5-9398-F695ACD76A62";
        String modulename = "工厂资料";
        // getFlowModule_field_util.getflowcondition(str,recordid,modulename);
        Boolean con_result = getFlowModule_field_util.getflowcondition(str, recordid, modulename);
        System.out.println(con_result);

    }

    @Test
    public
    void getspname() throws DocumentException {
        String str = " Self.QueryRecordValue('部门经理')";
        String recordid = "C43C1375-B50B-4931-A5DC-864567DBEA0C";
        String modulename = "付款申请";
        // getFlowModule_field_util.getflowcondition(str,recordid,modulename);
        String con_result = getFlowModule_field_util.getflowspname(str, recordid, modulename, true);
        System.out.println(con_result);

    }


    @Test
    public
    void split_str() throws DocumentException {

//        int result1 = "abc".indexOf("abc");
//        System.out.println(result1);
//        System.exit(0);

//        String str=" (htxz='库存采购')and ((pos('A51',bm)>0) or (pos('A32',bm)>0)or (pos('A26',bm)>0)) ";
//        String str=" (htxz='库存采购')and (((pos('事业八部',bm)>0) and  (pos('A32',bm)=0)) or (pos('事业五部',bm)>0)) ";
        String str = "pos('B32',self.QueryRecordValue('内部核算'))>0 or pos('B32',self.QueryRecordValue('部门'))>0 ";

        //str=str.replaceAll("'", "\"");
        String regex = "self.QueryRecordValue\\('(.*?)'";
        String sql = "";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        String maintablename = "";
        String subtablename = "";
        String recordid = "";
        recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
        Map<String, Object> mapList = new HashMap<>();
        List<Module_Field> module_fieldList = Workflow.getmodle_fieldlist("赊销额度申请");
        while (m.find()) {
            String name = m.group(1);

            System.out.println(name);
            List<Module_Field> module_fieldList_temp = new ArrayList<Module_Field>();
            module_fieldList_temp = module_fieldList.stream().filter(user -> name.equals(user.getName())).collect(Collectors.toList());

            System.out.println(module_fieldList_temp);
            if (module_fieldList_temp.size() > 0) {


                Module_Field module_field = module_fieldList_temp.get(0);
                String fieldname = module_field.getFieldname();
                str = str.replace("self.QueryRecordValue('" + name + "')", fieldname);
                if (!module_field.getIstable()) {
                    if (StringUtils.isEmpty(maintablename))
                        maintablename = module_field.getTablename();
                } else {
                    if (StringUtils.isEmpty(subtablename))

                        subtablename = module_field.getTablename();
                }

                sql = sql + module_field.getTablename() + "." + fieldname + " as " + fieldname + ",";

            }

        }
        System.out.println(str);
        //System.exit(0);
        if (sql.length() > 0) {
            sql = sql.substring(0, sql.length() - 1);
            System.out.println(sql);
            sql = " select top 1 " + sql + " from " + maintablename;
            if (!StringUtils.isEmpty(subtablename))
                sql = sql + " inner join " + subtablename + " on " + maintablename + ".recordid=" + subtablename + ".parentid";
            Map<String, Object> params = new HashMap<>();

            params.clear();
            params.put("sql", sql + " where recordid=#{recordid}");
            params.put("recordid", recordid);

            List<Map<String, Object>> ans = sqlMapper.sqltest(params);
            if (ans.size() > 0) {
                mapList = ans.get(0);
                Set keyset = mapList.keySet();
                for (Object key : keyset) {
                    System.out.println(key + "-" + mapList.get(key));

                }
            }

        }
        if (mapList.size() > 0) {


            //System.exit(0);
            //System.out.println(str);
            regex = "pos(.*?)0";
            p = Pattern.compile(regex);
            m = p.matcher(str);
            while (m.find()) {
                String str1 = m.group(1);
                String str2 = str1.replace("(", "");
                str2 = str2.replace(")", "");
                str2 = str2.replace(">", "");
                str2 = str2.replace("<", "");
                str2 = str2.replace("=", "");
                String[] arraystr = str2.split("[,]");
                if (str1.contains(">"))
                    str2 = (arraystr[1] + ".contains(" + arraystr[0] + ")");
                else
                    str2 = ("!" + arraystr[1] + ".contains(" + arraystr[0] + ")");
                System.out.println(str2);
                //System.out.println("pos("+str1+")");

                str = str.replace("pos" + str1 + "0", str2);
                //System.out.println(str);

            }
            str = str.replaceAll("or", "||");
            str = str.replaceAll("and", "&&");
            str = str.replaceAll("=", "==");
            str = str.replaceAll("'", "\"");
            System.out.println(str);
            //System.exit(0);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            Set keyset = mapList.keySet();
            for (Object key : keyset) {
                System.out.println(key + "-" + mapList.get(key));
                engine.put(String.valueOf(key), mapList.get(key));


            }
//            engine.put("htxz", "库存采购");
//            engine.put("bm", "业务部\\事业八部\\公司三十二部\\A32");
            //engine.put("c",true);
            Object result = null;
            try {
                result = engine.eval(str);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
        }
    }
    @Test
    public void getJsValue() throws Exception{
        //该函数测试Java获取JS变量值的能力
          String str="";
            str = "  var msg='hello';          "
                    + "  var number = 123;         "
                    + "  var sum = 0;         "
                    + "  var array=['A','B','C'];  "
                    + "  var json={                "
                    + "      'name':'pd',          "
                    + "      'subjson':{           "
                    + "           'subname':'spd'  "
                    + "           ,'id':123        "
                    + "           }                "
                    + "      };                    ";
            //执行语句
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");

        engine.eval(str);

            str="msg+=' world';number+=5;sum=number*5";
            //再次执行
            engine.eval(str);
            //获取js变量msg（String类型）
            System.out.println(engine.get("msg"));
        System.out.println(engine.get("sum"));
            //获取js变量msg（int类型）
            System.out.println(engine.get("number"));
            //获取js变量array（数组）
            ScriptObjectMirror array=(ScriptObjectMirror) engine.get("array");
            //getSlot（int index）函数用于获取下标为index的值
            System.out.println(array.getSlot(0));
            //获取js变量json（json类型）
            ScriptObjectMirror json=(ScriptObjectMirror) engine.get("json");
            //get（String key）函数用于键key的值
            System.out.println(json.get("name"));
            //获取js变量subjson（嵌套json类型）
            ScriptObjectMirror subjson=(ScriptObjectMirror)json.get("subjson");
            System.out.println(subjson.get("subname"));
    }

    @Test
    public
    void exec_script() {

//        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
//        ScriptEngine nashorn = scriptEngineManager.getEngineByName("js");
//        Boolean flag = null;
//        try {
//            flag = (Boolean) nashorn.eval("9%3==0");
//        }catch(ScriptException e){
//            System.out.println("执行脚本错误: "+ e.getMessage());
//
//        }
//        System.out.println(flag);
        String str = "var a=1;var b=2;c=a+b ";

        // if (str.contains("pos"))
        // String str1=str.substring(str.indexOf("pos"),


        str = str.replaceAll("or", "||");
        str = str.replaceAll("and", "&&");
        str = str.replaceAll("=", "==");
        str = str.replaceAll("'", "\"");
        System.out.println(str);
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
//        engine.put("htxz", "库存采购");
//        engine.put("bm", "A52");
        //engine.put("c",true);
        Object result = null;
        try {
            result = engine.eval(str);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
    }

    @Test
    public
    void xmlpara_test() {
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = null;
        try {
            document = reader.read(new File("src/main/resources/xml/demo.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            System.out.println("======获取属性值======");
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getValue());
            }
            System.out.println("======遍历子节点======");
            Iterator iterator1 = stu.elementIterator();
            while (iterator1.hasNext()) {
                Element stuChild = (Element) iterator1.next();
                System.out.println("节点名：" + stuChild.getName() + "---节点值：" + stuChild.getStringValue());
            }
        }
    }



}
